<template>
  <el-dialog
    v-model="dialogVisible"
    title="组件管理器"
    width="700px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="component-manager-container">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleImportComponent">
          <el-icon><Plus /></el-icon>导入组件
        </el-button>
        <el-input
          v-model="searchQuery"
          placeholder="搜索组件..."
          clearable
          prefix-icon="Search"
          style="width: 220px; margin-left: auto;"
        />
      </div>

      <!-- 组件列表 -->
      <el-table
        :data="filteredComponents"
        style="width: 100%"
        border
        v-loading="isLoading"
        :empty-text="emptyText"
      >
        <el-table-column prop="name" label="组件名称" min-width="120">
          <template #default="{ row }">
            <div class="component-name">
              <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" min-width="100" />
        <el-table-column prop="category" label="分类" min-width="80" />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="author" label="作者" min-width="80" />
        <el-table-column prop="createdAt" label="添加时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleViewComponent(row)"
              :disabled="row.isBuiltIn"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleUnloadComponent(row)"
              :disabled="row.isBuiltIn"
            >
              卸载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshComponentList">刷新</el-button>
      </span>
    </template>

    <!-- 组件详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="组件详情"
      width="500px"
      append-to-body
    >
      <div v-if="selectedComponent" class="component-detail">
        <div class="detail-item">
          <span class="label">组件ID:</span>
          <span class="value">{{ selectedComponentId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">名称:</span>
          <span class="value">{{ selectedComponent.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型:</span>
          <span class="value">{{ selectedComponent.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">分类:</span>
          <span class="value">{{ selectedComponent.category }}</span>
        </div>
        <div class="detail-item">
          <span class="label">版本:</span>
          <span class="value">{{ selectedComponent.version }}</span>
        </div>
        <div class="detail-item">
          <span class="label">作者:</span>
          <span class="value">{{ selectedComponent.author || '未知' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">添加时间:</span>
          <span class="value">{{ formatDate(selectedComponent.createdAt) }}</span>
        </div>
        <div class="detail-item" v-if="selectedComponent.description">
          <span class="label">描述:</span>
          <div class="value description">{{ selectedComponent.description }}</div>
        </div>
        <div class="detail-item" v-if="selectedComponent.path">
          <span class="label">文件路径:</span>
          <div class="value">{{ selectedComponent.path }}</div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="danger" 
            @click="handleUnloadFromDetail" 
            :disabled="!selectedComponent || selectedComponent.isBuiltIn"
          >
            卸载组件
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue';
import { Plus, Search } from '@element-plus/icons-vue';
import componentLoader from '@/utils/componentLoader';
import { ElMessageBox, ElMessage } from 'element-plus';

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
}>();

// 本地状态
const dialogVisible = ref(props.visible);
const searchQuery = ref('');
const isLoading = ref(false);
const components = ref<any[]>([]);
const selectedComponentId = ref('');
const selectedComponent = ref<any>(null);
const detailDialogVisible = ref(false);

// 同步prop和内部状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    loadComponents();
  }
});

watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal);
});

// 空状态文本
const emptyText = computed(() => {
  return searchQuery.value 
    ? '没有找到匹配的组件' 
    : '没有已加载的自定义组件';
});

// 过滤组件列表
const filteredComponents = computed(() => {
  if (!searchQuery.value) return components.value;
  
  const query = searchQuery.value.toLowerCase();
  return components.value.filter(comp => 
    comp.name.toLowerCase().includes(query) || 
    comp.type.toLowerCase().includes(query) || 
    comp.category.toLowerCase().includes(query) ||
    (comp.author && comp.author.toLowerCase().includes(query))
  );
});

// 加载组件列表
const loadComponents = () => {
  isLoading.value = true;
  
  try {
    const registry = componentLoader.getRegistry();
    components.value = Object.entries(registry).map(([id, comp]) => ({
      id,
      name: comp.name,
      type: comp.type,
      category: comp.category,
      version: comp.version,
      author: comp.author,
      description: comp.description,
      createdAt: comp.createdAt,
      isBuiltIn: comp.isBuiltIn,
      icon: comp.icon,
      path: comp.path
    }));
  } catch (error) {
    console.error('加载组件列表失败:', error);
    ElMessage.error('加载组件列表失败');
  } finally {
    isLoading.value = false;
  }
};

// 刷新组件列表
const refreshComponentList = () => {
  loadComponents();
};

// 格式化日期
const formatDate = (date: Date) => {
  if (!date) return '未知';
  return new Date(date).toLocaleString();
};

// 导入组件
const handleImportComponent = () => {
  ElMessageBox.alert(
    `组件导入功能正在开发中，将支持从以下路径导入组件：
    - 项目根目录的 dynamic-components 文件夹
    - 用户选择的本地 .vue 文件
    
    您也可以直接将 .vue 组件文件放入 dynamic-components 文件夹，系统将自动检测并加载。`, 
    '导入自定义组件', 
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  );
};

// 查看组件详情
const handleViewComponent = (component: any) => {
  selectedComponentId.value = component.id;
  selectedComponent.value = component;
  detailDialogVisible.value = true;
};

// 卸载组件
const handleUnloadComponent = (component: any) => {
  if (component.isBuiltIn) {
    ElMessage.warning('内置组件无法卸载');
    return;
  }

  ElMessageBox.confirm(
    `确定要卸载组件 "${component.name}" 吗？此操作不可恢复，且可能影响已使用该组件的设计。`,
    '卸载组件',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const success = componentLoader.unloadComponent(component.id);
    if (success) {
      ElMessage.success(`组件 ${component.name} 已卸载`);
      loadComponents(); // 刷新列表
    } else {
      ElMessage.error(`卸载组件 ${component.name} 失败`);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 从详情对话框卸载组件
const handleUnloadFromDetail = () => {
  if (!selectedComponent.value || selectedComponent.value.isBuiltIn) return;
  
  ElMessageBox.confirm(
    `确定要卸载组件 "${selectedComponent.value.name}" 吗？此操作不可恢复，且可能影响已使用该组件的设计。`,
    '卸载组件',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const success = componentLoader.unloadComponent(selectedComponentId.value);
    if (success) {
      ElMessage.success(`组件 ${selectedComponent.value.name} 已卸载`);
      detailDialogVisible.value = false;
      loadComponents(); // 刷新列表
    } else {
      ElMessage.error(`卸载组件 ${selectedComponent.value.name} 失败`);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.component-manager-container {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.component-name {
  display: flex;
  align-items: center;
}

.component-name .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.component-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
}

.detail-item .label {
  width: 80px;
  color: #909399;
  font-weight: 500;
  text-align: right;
  padding-right: 10px;
}

.detail-item .value {
  flex: 1;
  word-break: break-all;
}

.detail-item .description {
  white-space: pre-line;
  color: #606266;
  line-height: 1.5;
}
</style> 